#pragma once
#include <iostream>
#include <ctime>
#include <unistd.h>
#include <cstring>
#include "socket.hpp"
#include "protocol.hpp"

class tcpClient
{
public:
    tcpClient(const std::string &ip, uint16_t port)
        : _ip(ip), _port(port)
    {
    }
    ~tcpClient()
    {
    }
    void run()
    {
        srand((unsigned int)time(nullptr));
        if (!_sock.Connect(_ip, _port))
            exit(-1);
        const char *opr = {"+-*/%&^"};
        int count=1;
        while (count<=10)
        {
            // 生产数据
            int x = rand() % 100;
            usleep(500);
            int y = rand() % 100;
            char op = opr[rand() % strlen(opr)];
            // 通过协议将数据序列化
            request req(x, op, y);
            std::string massage;
            req.serialize(massage);
            req.CreateQeq();//输出创建好的请求
            encap(massage);
            //序列化完成，发送到服务器
            //lg(DEBUG, "\n%s", massage.c_str());//debug查看发送的信息
            

            int ret=write(_sock.getsock(), massage.c_str(), massage.size());
            if(ret==-1)
            {
                std::cout<<"write fail!"<<std::endl;
            }
            count++;

            char buffer[128]={0};
            int n=read(_sock.getsock(),buffer,sizeof(buffer));
            if(n==0)
            {
                lg(FATAL,"can't connect server!");
                exit(-1);
            }
            buffer[n]='\0';
            response res;
            massage=buffer;
            std::string data;
            unpack(massage,data);
            res.deserialize(data);

            res.getRes();
        }



        //我们还需要接收服务器返回的数据
        //......

        _sock.Close();
    }

private:
    Socket _sock;
    std::string _ip;
    uint16_t _port;
};